package com.github.jiangxch.rpc.transport.exchanger.jdk;

import com.github.jiangxch.rpc.transport.exchanger.Request;
import com.github.jiangxch.rpc.transport.exchanger.Response;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: jiangxch
 * @date: 2021/2/26 上午1:15
 */
public class FutureManager {
    private static Map<String, CompletableFuture<Object>> requestIdRequestFutureMap = new ConcurrentHashMap<>();
    
    public static CompletableFuture<Object> newRequestFuture(Request request) {
        CompletableFuture<Object> future = new CompletableFuture<>();
        requestIdRequestFutureMap.put(request.getRequestId(),future);
        return future;
    }
    
    public static void receiveResponse(Response response) {
        CompletableFuture<Object> future = requestIdRequestFutureMap.remove(response.getRequestId());
        if (future != null) {
            future.complete(response.getResult());
        }
    }
    
}
